﻿using Entity = Ruirun.Mes.Entities.IPN;
using IContractService = Ruirun.Mes.IMesService;
using InputDto = Ruirun.Mes.Dtos.IPNInputDto;
using OutputDto = Ruirun.Mes.Dtos.IPNOutputDto;

namespace Ruirun.Mes.Api.Areas.Admin.Controllers
{
    [Description("IPN")]
    [ModuleInfo(OrderNo = 5, Position = "Wms", PositionName = "仓储模块")]
    public class IPNController : AdminControllerBase
    {
        /// <summary>
        /// 获取 服务接口
        /// </summary>
        protected IContractService ContractService => ServiceProvider.GetService<IContractService>();

        #region 基础功能
        /// <summary>
        /// 读取
        /// </summary>
        [HttpPost]
        [Description("读取")]
        [ModuleInfo]
        public PageData<OutputDto> Read(PageRequest request)
        {
            Check.NotNull(request, nameof(request));
            IFunction function = this.GetExecuteFunction();
            Expression<Func<Entity, bool>> predicate = FilterService.GetExpression<Entity>(request.FilterGroup);
            var pageData = ContractService.IPNs.Include(a => a.MaterialCategory).ToPage(predicate, request.PageCondition, m => new
            {
                D = m,
                MaterialName = m.MaterialCategory.Name
            });

            var page = pageData.ToPageResult(data => data.Select(m =>
            {
                var outDto = m.D.MapTo<OutputDto>();
                return outDto;
            }).ToArray());

            //var page = CacheService.ToPageCache<Entity, OutputDto>(ContractService.IPNs, predicate, request.PageCondition,
            //   function);
            return page.ToPageData();
        }

        /// <summary>
        /// 读取选择
        /// </summary>
        [HttpPost]
        [Description("读取选择")]
        [ModuleInfo]
        public PageData<OutputDto> ReadIPN(PageRequest request)
        {
            Check.NotNull(request, nameof(request));
            IFunction function = this.GetExecuteFunction();
            Expression<Func<Entity, bool>> predicate = FilterService.GetExpression<Entity>(request.FilterGroup);
            var pageData = ContractService.IPNs.Include(a => a.MaterialCategory).ToPage(predicate, request.PageCondition, m => new
            {
                D = m,
                MaterialName = m.MaterialCategory.Name
            });

            var page = pageData.ToPageResult(data => data.Select(m =>
            {
                var outDto = m.D.MapTo<OutputDto>();
                return outDto;
            }).ToArray());

            //var page = CacheService.ToPageCache<Entity, OutputDto>(ContractService.IPNs, predicate, request.PageCondition,
            //   function);
            return page.ToPageData();
        }

        /// <summary>
        /// 新增
        /// </summary>
        [HttpPost]
        [DependOnFunction(nameof(Read))]
        [UnitOfWork]
        [Description("新增")]
        [ModuleInfo]
        public async Task<AjaxResult> Create(InputDto[] dtos)
        {
            Check.NotNull(dtos, nameof(dtos));
            List<string> ids = new();
            List<OutputDto> outputDtos = new();
            foreach (var dto in dtos)
            {
                var result = await ContractService.CreateIPNs(dto);
                if (!result.Succeeded)
                {
                    return result.ToAjaxResult();
                }
                ids.Add(dto.Id.ToString());
                outputDtos.Add(dto.MapTo<OutputDto>());
            }
            return AjaxResult.Success(outputDtos, $"{nameof(Entity)}“{ids.ExpandAndToString()}”创建成功");
        }

        /// <summary>
        /// 更新
        /// </summary>
        [HttpPost]
        [DependOnFunction(nameof(Read))]
        [UnitOfWork]
        [Description("更新")]
        [ModuleInfo]
        public async Task<AjaxResult> Update(InputDto[] dtos)
        {
            Check.NotNull(dtos, nameof(dtos));
            List<string> ids = new();
            List<OutputDto> outputDtos = new();
            foreach (var dto in dtos)
            {
                var result = await ContractService.UpdateIPNs(dto);
                if (!result.Succeeded)
                {
                    return result.ToAjaxResult();
                }
                ids.Add(dto.Id.ToString());
                outputDtos.Add(dto.MapTo<OutputDto>());
            }
            return AjaxResult.Success(outputDtos, $"{nameof(Entity)}“{ids.ExpandAndToString()}”更新成功");
        }

        /// <summary>
        /// 删除
        /// </summary>
        [HttpPost]
        [DependOnFunction(nameof(Read))]
        [UnitOfWork]
        [Description("删除")]
        [ModuleInfo]
        public async Task<AjaxResult> Delete(Guid[] ids)
        {
            Check.NotNull(ids, nameof(ids));
            var result = await ContractService.DeleteIPNs(ids);
            return result.ToAjaxResult();
        }
  
        [HttpPost]
        [Description("查找ipn信息")]
        public AjaxResult Get(string ipnNo)
        {
            Check.NotNullOrEmpty(ipnNo, nameof(ipnNo));
            var ipn = ContractService.IPNs.Where(a => a.IpnNo == ipnNo).Select(a => new
            {
                a.Id,
                a.Name,
                a.Description,
                a.Unit
            }).FirstOrDefault();

            return AjaxResult.Success(ipn);
        }

        #endregion

        #region 审批相关
        ///// <summary>
        ///// 提交研发审批
        ///// </summary>
        //[HttpPost]
        //[UnitOfWork]
        //[Description("提交研发审批")]
        //[ModuleInfo]
        //public async Task<AjaxResult> ApplyWaitToRd(Guid id)
        //{
        //    Check.NotEmpty(id, nameof(id));
        //    var operation = await ContractService.ApplyIPNHandler(id, Status.RdApprove);
        //    return operation.ToAjaxResult();
        //}

        ///// <summary>
        ///// 提交IPN审批
        ///// </summary>
        //[HttpPost]
        //[UnitOfWork]
        //[Description("提交IPN审批")]
        //[ModuleInfo]
        //public async Task<AjaxResult> ApplyRdToIpn(Guid id)
        //{
        //    Check.NotEmpty(id, nameof(id));
        //    var operation = await ContractService.ApplyIPNHandler(id, Status.IpnApprove);
        //    return operation.ToAjaxResult();
        //}

        ///// <summary>
        ///// 驳回至研发人员
        ///// </summary>
        //[HttpPost]
        //[UnitOfWork]
        //[Description("驳回至研发人员")]
        //[ModuleInfo]
        //public async Task<AjaxResult> ApplyRdToWait(Guid id)
        //{
        //    Check.NotEmpty(id, nameof(id));
        //    var operation = await ContractService.ApplyIPNHandler(id, Status.WaitApply);
        //    return operation.ToAjaxResult();
        //}

        ///// <summary>
        ///// 驳回至研发主管
        ///// </summary>
        //[HttpPost]
        //[UnitOfWork]
        //[Description("驳回至研发主管")]
        //[ModuleInfo]
        //public async Task<AjaxResult> ApplyIpnToRd(Guid id)
        //{
        //    Check.NotEmpty(id, nameof(id));
        //    var operation = await ContractService.ApplyIPNHandler(id, Status.RdApprove);
        //    return operation.ToAjaxResult();
        //}

        /// <summary>
        /// IPN分配完成
        /// </summary>
        [HttpPost]
        [DependOnFunction(nameof(Read))]
        [UnitOfWork]
        [Description("IPN分配完成")]
        [ModuleInfo]
        public async Task<AjaxResult> ApplyIpnToComplete(IPNDto dto)
        {
            Check.NotNull(dto, nameof(dto));

            var entity = ContractService.IPNs.AsTracking().FirstOrDefault(a => a.Id == dto.Id);
            Check.NotNull(entity, nameof(entity));

            entity.IpnNo = dto.IpnNo;
            var operation = await ContractService.UpdateIPN(entity);
            //if (operation.Succeeded)
            //{
            //    operation = await ContractService.ApplyIPNHandler(entity.Id, Status.CompleteApply);
            //}
            return operation.ToAjaxResult();
        }

        #endregion    

    }
}